package com.xyzwps.lib.openapi.ui;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap;

public class Load {

    private static final ConcurrentHashMap<String, String> cache = new ConcurrentHashMap<>();

    public static String load(String fileName) {
        var path = "META-INF/resources/webjars/swagger-ui-dist/5.17.14/" + fileName;
        return cache.computeIfAbsent(path, Load::_load);
    }

    private static String _load(String path) {
        var res = Load.class.getClassLoader().getResource(path);
        if (res == null) {
            return null;
        }

        try {
            try (var is = res.openStream()) {
                try (var reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
                    try (var writer = new StringWriter()) {
                        reader.transferTo(writer);
                        return writer.toString();
                    }
                }
            }
        } catch (IOException e) {
            return null;
        }
    }

    public static void main(String[] args) {
        System.out.println(Load.load("index.html"));
    }

}
